package com.zbkj.crmeb.plat.by.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.PageParamRequest;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.exception.ExceptionCodeEnum;
import com.doudian.open.api.product_getCatePropertyV2.ProductGetCatePropertyV2Request;
import com.doudian.open.api.product_getCatePropertyV2.ProductGetCatePropertyV2Response;
import com.doudian.open.api.product_getCatePropertyV2.data.DataItem;
import com.doudian.open.api.product_getCatePropertyV2.param.ProductGetCatePropertyV2Param;
import com.doudian.open.api.product_listV2.ProductListV2Request;
import com.doudian.open.api.product_listV2.ProductListV2Response;
import com.doudian.open.api.product_listV2.param.ProductListV2Param;
import com.doudian.open.api.shop_getShopCategory.ShopGetShopCategoryRequest;
import com.doudian.open.api.shop_getShopCategory.ShopGetShopCategoryResponse;
import com.doudian.open.api.shop_getShopCategory.param.ShopGetShopCategoryParam;
import com.doudian.open.api.supplyChain_batchGetCargoDetail.data.PropVal;
import com.doudian.open.api.supplyChain_queryBrandList.data.BrandListItem;
import com.doudian.open.api.supplyChain_queryCatePropList.SupplyChainQueryCatePropListRequest;
import com.doudian.open.api.supplyChain_queryCatePropList.SupplyChainQueryCatePropListResponse;
import com.doudian.open.api.supplyChain_queryCatePropList.data.CategoryPropListItem;
import com.doudian.open.api.supplyChain_queryCatePropList.data.Data;
import com.doudian.open.api.supplyChain_queryCatePropList.data.PropValItem;
import com.doudian.open.api.supplyChain_queryCatePropList.param.SupplyChainQueryCatePropListParam;
import com.doudian.open.api.warehouse_list.WarehouseListRequest;
import com.doudian.open.api.warehouse_list.WarehouseListResponse;
import com.doudian.open.api.warehouse_list.data.WarehousesItem;
import com.doudian.open.api.warehouse_list.param.Addr;
import com.doudian.open.api.warehouse_list.param.WarehouseListParam;
import com.doudian.open.core.AccessToken;
import com.doudian.open.core.AccessTokenBuilder;
import com.doudian.open.gson.JsonObject;
import com.doudian.open.utils.JsonUtil;
import com.factory.TaskParamsDto;
import com.factory.TaskProcessEngineFactory;
import com.google.gson.Gson;
import com.utils.SpringBeanUtil;
import com.zbkj.crmeb.chant.request.TikTokProductQueryRequest;
import com.zbkj.crmeb.enums.plat.PlatPushStatusEnums;
import com.zbkj.crmeb.handler.orderproduct.OrderProductContext;
import com.zbkj.crmeb.handler.orderproduct.OrderProductInterface;
import com.zbkj.crmeb.plat.by.dto.ByCommonConstant;
import com.zbkj.crmeb.plat.by.dto.PoizonPushInfo;
import com.zbkj.crmeb.plat.by.dto.Result;
import com.zbkj.crmeb.plat.by.dto.TikTokPushInfo;
import com.zbkj.crmeb.plat.dto.PlatProductRequest;
import com.zbkj.crmeb.plat.enums.MerPlatEnums;
import com.zbkj.crmeb.plat.tiktok.TikTokCountryInfoEnum;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.service.RelationService;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductDescriptionService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.task.plat.poizon.PoizonApi;
import com.zbkj.crmeb.task.plat.poizon.dto.PoizonResponseBodyDto;
import com.zbkj.crmeb.task.plat.tiktok.TikTokApi;
import net.logstash.logback.composite.JsonWritingUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.jboss.marshalling.ObjectTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: wsl
 * @date: 2024/3/10 0010 22:22
 * @ClassName: PlatProductServiceImpl
 */
@Service
public class PlatProductServiceImpl implements PlatProductService{
    private static final Logger logger = LoggerFactory.getLogger(PlatProductServiceImpl.class);
    @Autowired
    private StoreProductService storeProductService;
    @Resource
    private RelationService relationService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private StoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    PoizonApi poizonApi;
    @Autowired
    TikTokApi tikTokApi;

    @Value("${by.push.product.merIds}")
    private List<Integer> canPushByMerIds;

    @Override
    public CommonResult<List<String>> pushProduct(PlatProductRequest platProductRequest, Integer merId) {
        if (!canPushByMerIds.contains(merId)){
            return CommonResult.failed("当前商户不允许推送平台，请联系管理员确认");
        }

        if (null == platProductRequest || null == merId) {
            return CommonResult.failed("请求参数为空");
        }
        MerPlatEnums merPlatEnum = MerPlatEnums.getEnumByMerId(merId);
        if (null == merPlatEnum) {
            return CommonResult.failed("当前商户不允许推送平台，请联系管理员确认");
        }
        // 校验信息
        validateReqData(platProductRequest,merPlatEnum);

        StoreProduct storeProduct = storeProductService.getById(platProductRequest.getProductId());
        List<StoreProductAttrValue> storeProductAttrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId,Integer.valueOf(platProductRequest.getProductId()))
                .gt(StoreProductAttrValue::getStock,0));

        if (null == storeProduct || CollectionUtils.isEmpty(storeProductAttrValues)){
            return CommonResult.failed("商品信息查询失败，请稍后重试");
        }
        // 查询关联数据
        Relation productRelation = relationService.getOne(Wrappers.<Relation>lambdaQuery()
                .eq(Relation::getBusinessCode, String.valueOf(storeProduct.getId())).eq(Relation::getBusinessType,merPlatEnum.getBusinessType()));
        storeProduct.setPushRelations(productRelation);
        if (null != productRelation && Objects.equals(productRelation.getSubCode(),merPlatEnum.getPlatUp().getCode())){
            return CommonResult.failed("商品已推送过平台");
        }
        if ((null == platProductRequest.getSyncTask() || platProductRequest.getSyncTask()) && null!=productRelation && Objects.equals(productRelation.getFeature(ByCommonConstant.SUBMIT_TASK),ByCommonConstant.IS_Y)){
            return CommonResult.failed("商品已进入任务队列，请稍后查看推送结果");
        }
        // 进入任务队列
        if (pushTask(platProductRequest,storeProduct,merPlatEnum,String.valueOf(merId))){
            return CommonResult.success("推送成功");
        }
        Map<String, PlatProductRequest.skuInfo> map = platProductRequest.getPlatSkuInfos().stream().collect(Collectors.toMap(PlatProductRequest.skuInfo::getSourceSkuId, v -> v));
        for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
            if (!map.containsKey(storeProductAttrValue.getSourceSkuId())){
                continue;
            }
            PlatProductRequest.skuInfo skuInfo = map.get(storeProductAttrValue.getSourceSkuId());
            storeProductAttrValue.setPrice(skuInfo.getPrice());
        }
        Map<String, StoreProductAttrValue> sortMap = storeProductAttrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getSuk, v -> v, (v1, v2) -> {
            if (v1.getPrice().compareTo(v2.getPrice()) <= 0) {
                return v1;
            }
            return v2;
        }));
        // 取金额最小值
        if (MapUtils.isNotEmpty(sortMap)){
            storeProductAttrValues = new ArrayList<>();
            for (Map.Entry<String, StoreProductAttrValue> entry : sortMap.entrySet()) {
                storeProductAttrValues.add(entry.getValue());
            }
        }

        OrderProductContext orderProductContext = new OrderProductContext();
        orderProductContext.setStoreProduct(storeProduct);
        orderProductContext.setStoreProductAttrValues(storeProductAttrValues);
        orderProductContext.setCategoryId(platProductRequest.getCategoryId());
        orderProductContext.setBrandId(platProductRequest.getBrandId());
        orderProductContext.setPoizonPushInfo(platProductRequest.getPoizonPushInfo());
        orderProductContext.setTikTokPushInfo(platProductRequest.getTikTokPushInfo());
        orderProductContext.setMerId(merId);
        if ("TIKTOK".equals(merPlatEnum.getCode())) {
            // 查询商品详情
            StoreProductDescription storeProductDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
                    .eq(StoreProductDescription :: getProductId, platProductRequest.getProductId())
                    .last("LIMIT 1")
            );
            orderProductContext.setStoreProductDescription(storeProductDescription);
        }
        Result execute = SpringBeanUtil.getBean(merPlatEnum.getHandle(), OrderProductInterface.class).execute(orderProductContext);
        CommonResult<List<String>> commonResult = CommonResult.success();
        // 成功
        if (execute.isSuccess()){
            // 校验信息
            if (null != execute.getData()){
                commonResult.setData(JSON.parseArray(JSON.toJSONString(execute.getData()),String.class));
            }
            return commonResult;
        }
        commonResult.setMessage(execute.getMessage());
        // 失败
        if (null != execute.getData()){
            commonResult.setData(JSON.parseArray(JSON.toJSONString(execute.getData()),String.class));
            commonResult.setMessage(execute.getMessage()+";"+JSON.toJSONString(execute.getData()));
        }
        commonResult.setCode(ExceptionCodeEnum.FAILED.getCode());
        return commonResult;
    }

    private boolean pushTask(PlatProductRequest platProductRequest,StoreProduct storeProduct,MerPlatEnums merPlatEnum,String merId) {
        if (null != platProductRequest.getSyncTask() && !platProductRequest.getSyncTask()){
            return false;
        }
        TaskParamsDto taskParamsDto = new TaskParamsDto();
        taskParamsDto.setTaskHandler(merPlatEnum.getTaskHandle());
        taskParamsDto.setPlatProductRequest(platProductRequest);
        taskParamsDto.setMerId(merId);
        Map<String, String> params = new HashMap<>();
        params.put("params",JSON.toJSONString(taskParamsDto));
        Task task = Task.buildTask(platProductRequest.getProductId() + "_" + System.currentTimeMillis(), merPlatEnum.getDesc() +"推送商品:"+platProductRequest.getProductId(), params);
        TaskProcessEngineFactory.submitTask(task);
        Relation pushRelations = storeProduct.getPushRelations();
        if (null == pushRelations){
            pushRelations = Relation.buildRelation(String.valueOf(storeProduct.getId()),merPlatEnum.getBusinessType(),PlatPushStatusEnums.PUSH_TASK.getCode());
        }
        pushRelations.addFeature(ByCommonConstant.SUBMIT_TASK,ByCommonConstant.IS_Y);
        pushRelations.addFeature(ByCommonConstant.MER_ID,merId);
        if (null == pushRelations.getId()){
            relationService.save(pushRelations);
            return true;
        }
        relationService.updateById(pushRelations);
        return true;
    }

    @Override
    public CommonResult<Object> updateProduct(PlatProductRequest platProductRequest, Integer merId) {
        StoreProduct storeProduct = storeProductService.getById(platProductRequest.getProductId());
        MerPlatEnums merPlatEnum = MerPlatEnums.getEnumByMerId(merId);
        if (null == merPlatEnum) {
            return CommonResult.failed("当前商户不允许推送，请联系管理员确认");
        }
        List<StoreProductAttrValue> storeProductAttrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId,Integer.valueOf(platProductRequest.getProductId()))
                .gt(StoreProductAttrValue::getStock,0));

        if (null == storeProduct || CollectionUtils.isEmpty(storeProductAttrValues)){
            return CommonResult.failed("商品信息查询失败，请稍后重试");
        }
        Iterator<StoreProductAttrValue> iterator = storeProductAttrValues.iterator();
        while (iterator.hasNext()){
            StoreProductAttrValue next = iterator.next();
            if (Objects.equals(next.getFeature(ByCommonConstant.PUSH_PLAT),"Y")){
                iterator.remove();
            }
        }
        if (CollectionUtils.isEmpty(storeProductAttrValues)){
            return CommonResult.failed("商品已推送过平台");
        }

        Map<String, PlatProductRequest.skuInfo> map = platProductRequest.getPlatSkuInfos().stream().collect(Collectors.toMap(PlatProductRequest.skuInfo::getSourceSkuId, v -> v));
        for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
            if (!map.containsKey(storeProductAttrValue.getSourceSkuId())){
                continue;
            }
            PlatProductRequest.skuInfo skuInfo = map.get(storeProductAttrValue.getSourceSkuId());
            storeProductAttrValue.setPrice(skuInfo.getPrice());
        }
        OrderProductContext orderProductContext = new OrderProductContext();
        orderProductContext.setStoreProduct(storeProduct);
        orderProductContext.setStoreProductAttrValues(storeProductAttrValues);
        Result execute = SpringBeanUtil.getBean(merPlatEnum.getHandle(), OrderProductInterface.class).execute(orderProductContext);
        CommonResult<List<String>> commonResult = CommonResult.success();
        // 成功
        if (execute.isSuccess()){
            // 校验信息
            if (null != execute.getData()){
                commonResult.setData(JSON.parseArray(JSON.toJSONString(execute.getData()),String.class));
            }
            return null;
        }
        // 失败
        if (null != execute.getData()){
            commonResult.setData(JSON.parseArray(JSON.toJSONString(execute.getData()),String.class));
        }
        commonResult.setCode(ExceptionCodeEnum.FAILED.getCode());
        commonResult.setMessage(execute.getMessage());
        return null;
    }

    private void validateReqData(PlatProductRequest platProductRequest, MerPlatEnums merPlatEnum) {
        if ("BY".equals(merPlatEnum.getCode())) {
            if (StringUtils.isBlank(platProductRequest.getBrandId())||StringUtils.isBlank(platProductRequest.getCategoryId())){
                throw new CrmebException("品牌ID或类目ID为空");
            }
        } else if ("POIZON".equals(merPlatEnum.getCode())) {
                PoizonPushInfo poizonPushInfo = platProductRequest.getPoizonPushInfo();
                poizonPushInfo.getBrandData().setBrandList(new ArrayList<>());
                poizonPushInfo.getCategoryData().setCategoryList(new ArrayList<>());
                poizonPushInfo.getGanderData().setGanderList(new ArrayList<>());
                poizonPushInfo.getSizeTypeData().setSizeTypeList(new ArrayList<>());
                StringBuilder message = new StringBuilder();
                if(StringUtils.isBlank(poizonPushInfo.getBrandData().getCheckItem())) {
                    message.append("品牌未选择").append(",");
                }
                if(StringUtils.isBlank(poizonPushInfo.getCategoryData().getCheckItem())) {
                    message.append("类目未选择").append(",");
                }
                if(StringUtils.isBlank(poizonPushInfo.getGanderData().getCheckItem())) {
                    message.append("所属性别未选择").append(",");
                }
                if(StringUtils.isBlank(poizonPushInfo.getSizeTypeData().getCheckItem())) {
                    message.append("尺码标准未选择").append(",");
                }
                if (StringUtils.isNotBlank(message)) {
                    throw new CrmebException(message.toString());
                }
        } else if ("TIKTOK".equals(merPlatEnum.getCode())) {
            StringBuilder message = new StringBuilder();
            TikTokPushInfo tikTokPushInfo = platProductRequest.getTikTokPushInfo();
            List<TikTokPushInfo.Prop> tikTokBatchPropList = tikTokPushInfo.getTikTokBatchPropList();
            List<TikTokPushInfo.Prop> tikTokCategoryPropList = tikTokPushInfo.getTikTokCategoryPropList();
            List<TikTokPushInfo.Prop> tikTokPeriodPropList = tikTokPushInfo.getTikTokPeriodPropList();
            List<TikTokPushInfo.Prop> tikTokSalePropList = tikTokPushInfo.getTikTokSalePropList();
            List<TikTokPushInfo.Prop> tikTokSkuCategoryPropList = tikTokPushInfo.getTikTokSkuCategoryPropList();
            List<TikTokPushInfo.ProductProp> tikTokProductPropList = tikTokPushInfo.getTikTokProductPropList();

            if (Objects.isNull(tikTokPushInfo.getCategoryId())) {
                message.append("商品类目未选择").append(",");
            }
            if (Objects.isNull(tikTokPushInfo.getProductName())) {
                message.append("商品名称不能为空").append(",");
            }
            if (!Objects.isNull(tikTokPushInfo.getProductName())) {
                String productNamePre = tikTokPushInfo.getProductName();
                List<StoreProductAttrValue> attrValues = storeProductAttrValueService.getListByProductId(Integer.parseInt(platProductRequest.getProductId()));
                for (StoreProductAttrValue attrValue : attrValues) {
                    String productName = productNamePre + " " + attrValue.getSuk();
                    if (StrLength(productName) > 60) {
                        message.append("商品名称最多支持输入30个汉字，60个字符,商品名称请不要包含品牌信息").append(",");
                        break;
                    }
                }
            }
            if (Objects.isNull(tikTokPushInfo.getOutWarehouseId())) {
                message.append("商品仓库未选择").append(",");
            }
            if (Objects.isNull(tikTokPushInfo.getPreSellType())) {
                message.append("商品发货模式未选择").append(",");
            }
            if (CollectionUtils.isEmpty(tikTokBatchPropList)) {
                message.append("批次信息未填").append(",");
            }
            if (CollectionUtils.isEmpty(tikTokCategoryPropList)) {
                message.append("类目信息未填").append(",");
            }
            if (CollectionUtils.isEmpty(tikTokPeriodPropList)) {
                message.append("销售信息未填").append(",");
            }
            if (CollectionUtils.isEmpty(tikTokSalePropList)) {
                message.append("销售信息未填").append(",");
            }
//            if (CollectionUtils.isEmpty(tikTokSkuCategoryPropList)) {
//                message.append("库存信息未填").append(",");
//            }
            if (CollectionUtils.isEmpty(tikTokProductPropList)) {
                message.append("参数未填校验失败").append(",");
            }
            for (TikTokPushInfo.Prop prop : tikTokBatchPropList) {
                if (prop.getIsRequired()) {
                    PropVal propVal = prop.getPropVal();
                    if (StringUtils.isBlank(propVal.getPropValue()) && Objects.isNull(propVal.getPropValueId())) {
                        message.append(prop.getPropKey().getPropKey()).append("未填(选)").append(",");
                    }
                    if ("否".equals(propVal.getPropValue())) {
                        message.append(prop.getPropKey().getPropKey()).append("必须选【是】").append(",");
                    }
                }
            }
            for (TikTokPushInfo.Prop prop : tikTokCategoryPropList) {
                if (prop.getIsRequired()) {
                    PropVal propVal = prop.getPropVal();
                    if (StringUtils.isBlank(propVal.getPropValue()) && Objects.isNull(propVal.getPropValueId())) {
                        message.append(prop.getPropKey().getPropKey()).append("未填(选)").append(",");
                    }
                }
            }
            for (TikTokPushInfo.Prop prop : tikTokPeriodPropList) {
                if (prop.getIsRequired()) {
                    PropVal propVal = prop.getPropVal();
                    if (StringUtils.isBlank(propVal.getPropValue()) && Objects.isNull(propVal.getPropValueId())) {
                        message.append(prop.getPropKey().getPropKey()).append("未填(选)").append(",");
                    }
                }
            }
            for (TikTokPushInfo.Prop prop : tikTokSalePropList) {
                if (prop.getIsRequired()) {
                    PropVal propVal = prop.getPropVal();
                    if (StringUtils.isBlank(propVal.getPropValue()) && Objects.isNull(propVal.getPropValueId())) {
                        message.append(prop.getPropKey().getPropKey()).append("未填(选)").append(",");
                    }
                }
            }
//            for (TikTokPushInfo.Prop prop : tikTokSkuCategoryPropList) {
//                if (prop.getIsRequired()) {
//                    PropVal propVal = prop.getPropVal();
//                    if (StringUtils.isBlank(propVal.getPropValue()) && Objects.isNull(propVal.getPropValueId())) {
//                        message.append(prop.getPropKey().getPropKey()).append("未填(选)").append(",");
//                    }
//                }
//            }
            for (TikTokPushInfo.ProductProp prop : tikTokProductPropList) {
                if (prop.getRequired()) {
                    if (CollectionUtils.isEmpty(prop.getValueList()) && Objects.isNull(prop.getValue())) {
                        message.append(prop.getPropertyName()).append("未填(选)").append(",");
                    }
                }
            }
//            platProductRequest.setSyncTask(false);
            if (StringUtils.isNotBlank(message)) {
                throw new CrmebException(message.toString());
            }
        }
    }

    private int StrLength(String value) {
        int length = 0;
        String chinese = "[\u4e00-\u9fa5]";
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length;
    }

    @Override
    public CommonResult<Object> getPoizonPushInfo(Integer productId, Integer merId) {
        String logID = UUID.randomUUID().toString();
        logger.info("logID:[{}]", logID);
        logger.info("[{}] getPoizonPushInfo 入口", logID);

        PoizonPushInfo poizonPushInfo = new PoizonPushInfo();

        // 获取品牌
        PoizonResponseBodyDto<List<PoizonResponseBodyDto.BrandDataDTO>> brandList = poizonApi.getBrandList();
        PoizonPushInfo.BrandData brandData = new PoizonPushInfo.BrandData();
        brandData.setBrandList(brandList.getData());
        brandData.setCheckItem("");
        poizonPushInfo.setBrandData(brandData);

        //获取三级类目
        PoizonResponseBodyDto<List<PoizonResponseBodyDto.CategoryDataDTO>> categoryList = poizonApi.getCategoryList();
        PoizonPushInfo.CategoryData categoryData = new PoizonPushInfo.CategoryData();

        categoryData.setCategoryList(categoryList.getData());
        categoryData.setCheckItem("");
        poizonPushInfo.setCategoryData(categoryData);

        //获取性别
        PoizonResponseBodyDto<List<PoizonResponseBodyDto.GenderDataDTO>> genderList = poizonApi.getGenderList();
        PoizonPushInfo.GanderData ganderData = new PoizonPushInfo.GanderData();
        List<PoizonResponseBodyDto.GenderDataDTO> collect = genderList.getData();
        collect.removeIf(i->i.getId() > 1000L);
        ganderData.setGanderList(collect);
        ganderData.setCheckItem("");
        poizonPushInfo.setGanderData(ganderData);

        // 获取尺寸标准
        PoizonPushInfo.SizeTypeData sizeTypeData = new PoizonPushInfo.SizeTypeData();
        List<Object> sizeTypeList = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("id",1);
        map1.put("sizeType","IT");
        sizeTypeList.add(map1);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("id",2);
        map2.put("sizeType","US");
        sizeTypeList.add(map2);
        Map<String, Object> map3 = new HashMap<>();
        map3.put("id",3);
        map3.put("sizeType","EU");
        sizeTypeList.add(map3);
        sizeTypeData.setSizeTypeList(sizeTypeList);
        sizeTypeData.setCheckItem("");
        poizonPushInfo.setSizeTypeData(sizeTypeData);
        return CommonResult.success(poizonPushInfo);
    }

    @Override
    public CommonResult<Object> getTikTokGoodsCategoryList(Integer productId, Integer merId,Long cid) {
        AccessToken accessToken = AccessTokenBuilder.build(TikTokApi.getShopId(merId));
        return CommonResult.success(tikTokApi.getTikTokGoodsCategoryList(cid, accessToken));
    }

    @Override
    public CommonResult<Object> getTikTokGoodsBrandList(Integer productId, Long categoryPid,Long categoryCid, Integer merId) {
        List<Long> idList = new ArrayList<>();
        if (Objects.isNull(categoryPid)) {
            return CommonResult.success(new ArrayList<>());
        }
        AccessToken accessToken = AccessTokenBuilder.build(TikTokApi.getShopId(merId));

        List<com.doudian.open.api.brand_list.data.AuthBrandListItem> brandListResult = tikTokApi.getAllBrand(categoryPid, accessToken);

        return CommonResult.success(brandListResult);
    }

    @Override
    public CommonResult<Object> getCategoryProp(Integer productId, Long categoryCid, Integer merId) {
        Map<String, Object> resObj = new HashMap<>();
        AccessToken accessToken = AccessTokenBuilder.build(TikTokApi.getShopId(merId));
        {
            SupplyChainQueryCatePropListRequest request = new SupplyChainQueryCatePropListRequest();
            SupplyChainQueryCatePropListParam param = request.getParam();
            param.setCategoryId(categoryCid);
            param.setItemType(1);
            param.setBmpCode("xiaodian.crossborder");
            SupplyChainQueryCatePropListResponse response = request.execute(accessToken);
            if (response.isSuccess()) {
                Data data = response.getData().getData();
                for (CategoryPropListItem categoryPropListItem : data.getCategoryPropList()) {
                    if ("brand_location".equals(categoryPropListItem.getPropKey().getPropCode())) {
                        ArrayList<PropValItem> propVal = new ArrayList<>();
                        for (TikTokCountryInfoEnum value : TikTokCountryInfoEnum.values()) {
                            PropValItem propValItem = new PropValItem();
                            propValItem.setPropValue(value.getName());
                            propValItem.setPropValueId(value.getId());
                            propVal.add(propValItem);
                        }
                        categoryPropListItem.setPropVal(propVal);
                    }
                }
                resObj.put("cargoProp",data);
            }
        }

        {
            ProductGetCatePropertyV2Request request = new ProductGetCatePropertyV2Request();
            ProductGetCatePropertyV2Param param = request.getParam();
            param.setCategoryLeafId(categoryCid);
            ProductGetCatePropertyV2Response response = request.execute(accessToken);
            if (response.isSuccess()) {
                List<DataItem> data = response.getData().getData();
                resObj.put("productProp",data);
            }
        }
        if (resObj.size() != 2) {
            CommonResult.failed("获取信息失败");
        }
        return CommonResult.success(resObj);
    }

    @Override
    public List<Map<String, Object>> getTikTokProductList(PageParamRequest pageParamRequest, TikTokProductQueryRequest productQueryRequest, Integer merId) {
        AccessToken accessToken = AccessTokenBuilder.build(TikTokApi.getShopId(merId));
        ProductListV2Request request = new ProductListV2Request();
        ProductListV2Param param = request.getParam();
        param.setPage((long) pageParamRequest.getPage());
        param.setSize((long) pageParamRequest.getLimit());
        param.setCheckStatus(3L);
        param.setName(productQueryRequest.getName());
        ProductListV2Response response = request.execute(accessToken);
        if (response.isSuccess()) {
            return response.getData().getData().stream().map(dataItem -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", dataItem.getProductId());
                map.put("name", dataItem.getName());
                return map;
            }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public CommonResult<Object> getTikTokWarehouseList(Integer productId, Integer merId) {
        long page = 0;
        AccessToken accessToken = AccessTokenBuilder.build(TikTokApi.getShopId(merId));
        List<WarehousesItem> warehousesItemList = new ArrayList<>();
        WarehouseListRequest request = new WarehouseListRequest();
        WarehouseListParam param = request.getParam();
        param.setOrderBy("create_time");
        param.setRank("desc");
        param.setSize(10L);
        while (true) {
            param.setPage(page);
            WarehouseListResponse response = request.execute(accessToken);
             if (response.isSuccess()) {
                 warehousesItemList.addAll(response.getData().getWarehouses());
                 if (CollectionUtil.isEmpty(response.getData().getWarehouses())) {
                     break;
                 }
                 page++;
             }
        }
        return CommonResult.success(warehousesItemList);
    }
}
